// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { Handler } from "./ProgressMgr";

const {ccclass, property} = cc._decorator;


@ccclass
export class LinkNode<T> {
    data: Handler<T>;
    prev: LinkNode<T>;
    next: LinkNode<T>;
    constructor(data: Handler<T>) {
        this.data = data;
        this.prev = null;
        this.next = null;
    }
}
export default class LinkedList<T> {
    head: LinkNode<T>;
    current: LinkNode<T>;
    size: number;
    constructor() {
        this.head = null;
        this.size = 0;
    }
    //在全部append完成之后初始化current，current只需要初始化一次，请勿重复初始化current
    initCurrent() {
        this.current = this.head;
    }

    // 添加节点到列表末尾
    append(data: LinkNode<T>) {
        const newNode = data;
        if (this.head === null) {
            this.head = newNode;
            newNode.prev = newNode;
            newNode.next = newNode;
            
        } else {
            const tail = this.head.prev; // 获取尾节点
            tail.next = newNode;
            newNode.prev = tail;
            newNode.next = this.head;
            this.head.prev = newNode;
        }
        this.size++;
    }

    // 删除指定数据的节点
    remove(data) {
        if (this.size === 0) return false;

        let current = this.head;
        let deleted = false;

        // 如果只有一个节点
        if (this.size === 1 && this.head.data === data) {
            this.head = null;
            this.size--;
            return true;
        }

        do {
            if (current.data === data) {
                current.prev.next = current.next;
                current.next.prev = current.prev;

                if (current === this.head) { // 如果是头节点，更新头节点
                    this.head = current.next;
                }

                this.size--;
                deleted = true;
                break;
            }
            current = current.next;
        } while (current !== this.head);

        return deleted;
    }

    // 打印列表数据
    print() {
        if (this.size === 0) return 'Empty List';

        let current = this.head;
        let result = '';
        
            console.log(current.data);
            console.log(current.next.data);
            console.log(current.next.next.data);
    
            
        
        
        return result;
    }

    // 获取列表大小
    getSize() {
        return this.size;
    }
}
